package com.sr.wslr.service.elasticsearch;

import com.sr.wslr.service.elasticsearch.annotation.ESEntity;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ExecutionException;

@Component
public class ESUtils {

	@Autowired
	public Client client;
	
	@Value("${es.cfg.indexName}")
	public String indexName;
	
	public static void initIndexAndMapping(Client client, String index, Class<?> clazz) throws Exception{
		if(client == null || StringUtils.isBlank(index)){
			return;
		}
		// 如果不存在就创建索引  
        if (!client.admin().indices().prepareExists(index).get().isExists()) {  
            //client.admin().indices().prepareDelete(index).get(); 
            client.admin().indices().prepareCreate(index).execute().actionGet();
        }  
        
        ElasticConvertor covertor = (ElasticConvertor)clazz.newInstance();
        
		ESEntity esEntity = (ESEntity)clazz.getAnnotation(ESEntity.class);
		String typeName = esEntity.name();
		if(StringUtils.isBlank(typeName)){
			throw new Exception("ESEntity name为空");
		}
		
		PutMappingRequest mapping = Requests.putMappingRequest(index).type(typeName).source(covertor.getMappingBuilder());
		client.admin().indices().putMapping(mapping).actionGet();
	}
	
	/**
	 * 添加文档
	 * @param convertor
	 */
	public void addDocument(ElasticConvertor convertor){
		if(client == null || convertor == null){
			return;
		}
		
		client.prepareIndex(indexName, convertor.getTypeName(), convertor.getId()).setSource(convertor.getJson()).get(); 
	}
	
	/**
	 * 更新文档
	 * @param id
	 * @param convertor
	 * @param params
	 * @return
	 */
	public boolean updateDocument(String id, ElasticConvertor convertor, Map<String, Object> params){
		if(client == null || params==null || id == null){
			return false;
		}
		try {
			UpdateRequest updateRequest = new UpdateRequest();
			updateRequest.index(indexName);
			updateRequest.type(convertor.getTypeName());
			updateRequest.id(id);
			updateRequest.doc(params);
			client.update(updateRequest).get();
			return true;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		} catch (ExecutionException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 删除文档
	 * @param id
	 * @param convertor
	 */
	public void delDocument(String id, ElasticConvertor convertor){
		if(client == null || id == null){
			return;
		}
		client.prepareDelete(indexName, convertor.getTypeName(),id)  
                .execute()  
                .actionGet();  
	}
	
}
